import { message } from 'antd';
import axios, {
  AxiosResponse,
  CreateAxiosDefaults,
  InternalAxiosRequestConfig,
  AxiosRequestConfig,
  AxiosError,
} from 'axios';
import { ApiResponse } from '@/types/api';
import { getAccessToken } from './storage';
const HOST = import.meta.env.VITE_APP_BASE_API;
const PREFIX = import.meta.env.VITE_APP_BASE_API_PREFIX;
const baseURL = `${HOST}/${PREFIX}`;
// 明确指定 http 实例的类型
const axiosConfig: CreateAxiosDefaults = {
  baseURL,
  timeout: 60 * 1000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
};

const instance = axios.create(axiosConfig);

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = getAccessToken();
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 修正响应拦截器的返回值类型
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status >= 200 && response.status <= 300 && response.data.code === 200) {
      return Promise.resolve(response.data);
    }
    message.error(response.data.message);
    return Promise.reject(response.data);
  },
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      message.error('登录已过期，请重新登录');
      localStorage.removeItem('persist:root');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  },
);

// 定义 http 函数的返回类型：直接返回 ApiResponse<T>
export default function http<T = unknown>(config: AxiosRequestConfig): Promise<ApiResponse<T>> {
  // 请求拦截器指定 config 类型

  return instance(config);
}
